#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define char2number(x)(x-'0'); // char to number

typedef struct ListNode{
    int value;
    struct ListNode *next;
}ListNode;

void show(ListNode *ln){
    int number=0, factor=1;
    while(ln!=0){
        number += ln->value * factor;
        factor *= 10;
        ln = ln->next;
    }
    printf("Number is: [%d]. \n", number);
}

static ListNode *build_from_chars(char *chs){
    ListNode *head=0, *temp=0, *prev=0;
    int first = 1;
    int len = strlen(chs);
    char *tail = chs + len - 1 ;
    while(len-- > 0){
        temp = (ListNode *)malloc(sizeof(ListNode));
        memset(temp, 0, sizeof(ListNode));
        temp->value = char2number(*tail--);
        if (first) {
            head = temp;
            first = 0;
        }else{
            prev->next = temp;
        }
        prev = temp;
    }
    return head;
}

static int add_two_listnode(ListNode *ln1, ListNode *ln2){
    int n1 = 0, n2 = 0;
    ListNode *l1 = ln1, *l2=ln2;
    int factor = 1;
    while(l1 != 0){
        n1 += l1->value * factor;
        l1 = l1->next;
        factor *= 10;
    }
    factor = 1;
    while(l2 != 0){
        n2 += l2->value * factor;
        l2 = l2->next;
        factor *= 10;
    }
    return n1 + n2;
}

static void free_listbode(ListNode *ln){
    ListNode *curr = ln, *rear = ln;
    while(curr != 0){
        rear = curr->next;
        free(curr);
        curr = rear;
    }
}
int main(int argc, char **argv){
    if (argc < 3){
        fprintf(stderr, "Usage: ./test n1, n2 \n");
        return 0;
    }
    ListNode *ln1 = build_from_chars(argv[1]);
    ListNode *ln2 = build_from_chars(argv[2]);

    show(ln1); show(ln2);

    int res = add_two_listnode(ln1, ln2);
    printf("%d \n", res);

    free_listbode(ln1);
    free_listbode(ln2);
    printf("Memory is freed! \n");
    return 0;
}
